using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using AutoGear.BLL;
using ECommerce.Library.DataStructure;
using ECommerce.Library.Web;
using ECommerce.Library;

public partial class myaccount_shopping_cart : SitePublicBasePage
{
    ShoppingCart _shoppingCart;
    ReadWriteCustomCollection<Favorites> _favorites;

    public String SupplierId
    {
        get
        {
            try
            {

                return Page.RouteData.Values["partnerId"].ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        uccResponseMessage.Visible = false;
        if (!Page.IsPostBack)
        {
            CheckoutStepsValidate();
            LoadSession();
            SaveFavoritesList();
            BindData();
        }
    }

    protected void SaveFavoritesList()
    {
        try
        {
            if (SessionManager.IsUserLoggedIn)
            {
                if (_favorites.Count > 0)
                {
                    int userId = SessionManager.IsUserLoggedIn ? SessionManager.LoggedUser.UserId : 0;
                    Favorites.SaveFavorites(this._favorites, userId, true);
                    this._favorites.Clear();
                    AutoGearSessionManager.FavoritesList = this._favorites;
                    uccResponseMessage.SetSuccessMessage(AutoGearCommonMessage.AddToShoppingListSuccessful);
                    uccResponseMessage.Visible = true;
                }
            }
        }
        catch
        {
            uccResponseMessage.SetFailMessage(AutoGearCommonMessage.AddToShoppingListFailed);
            uccResponseMessage.Visible = true;
        }
    }

    protected void BindData()
    {
        if (_shoppingCart.CartItems.Count > 0 || _shoppingCart.GiftItems.Count > 0)
        {
            if (_shoppingCart.CartItems.Count == 0)
            {
              rptShoppingCart.Visible = false;
            }
            else
            {
                rptShoppingCart.DataSource = _shoppingCart.CartItems;
                rptShoppingCart.DataBind();
            }

            if (_shoppingCart.GiftItems.Count == 0)
            {
                lblNoGift.Visible = true;
                rptShoppingCartForGift.Visible = false;
            }
            else
            {
                rptShoppingCartForGift.DataSource = _shoppingCart.GiftItems;
                rptShoppingCartForGift.DataBind();
            }

            pnlShoppingCart.Visible = true;
            pnlEmptyCart.Visible = false;
            imbCheckout.Visible = true;            
        }
        else
        {
            pnlShoppingCart.Visible = false;
            pnlEmptyCart.Visible = true;
            imbCheckout.Visible = false;
            uccResponseMessage.SetFailMessage("No product in shopping cart");
        }      
        
    }

    protected void LoadSession()
    {
        _shoppingCart = AutoGearSessionManager.ShoppingCart;
        _favorites = AutoGearSessionManager.FavoritesList;

        hplShippingPolicy.NavigateUrl = string.IsNullOrEmpty(SupplierId) ? AutoGear.BLL.CustomSiteMap.ShippingPolicy : "~/partner/" + SupplierId + "/privacy-policy.aspx";
    }

    protected void rptShoppingCart_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
            CheckBox cbxSelectAll = (CheckBox)e.Item.FindControl("cbxSelectAll");
            if (cbxSelectAll != null)
                cbxSelectAll.Attributes.Add("onclick", "javascript:SelectAll('" + rptShoppingCart.ClientID + "','" + cbxSelectAll.ClientID + "','cbxSelect')");
        }
        else if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            CartItem cartItem = (CartItem)e.Item.DataItem;
            if (cartItem.Product.ProductId > 0)
            {
                HiddenField hdfProductId = (HiddenField)e.Item.FindControl("hdfProductId");
                hdfProductId.Value = cartItem.Product.ProductId.ToString();

                Image imgItemImage = (Image)e.Item.FindControl("imgItemImage");
                imgItemImage.ImageUrl = ImageResizer.CheckImageMissing(cartItem.Product.ProductImageSmallThumbnail, AutoGear.BLL.SiteSettings.NoImageSmallThumbnailUrl);

                HyperLink hlkItem = (HyperLink)e.Item.FindControl("hlkItem");
                hlkItem.NavigateUrl = cartItem.Product.ProductUrl;
                hlkItem.Text = cartItem.Product.ProductName;

                Label lblItemNumber = (Label)e.Item.FindControl("lblItemNumber");
                lblItemNumber.Text = "Item Number: " + cartItem.Product.ItemNumber;

                Label lblItemPrice = (Label)e.Item.FindControl("lblItemPrice");

                if (string.IsNullOrEmpty(SupplierId))
                {
                    if (cartItem.Product.StandardCost > 0)
                    {
                        lblItemPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.Product.StandardCost + cartItem.Product.AdditionalPrice);
                    }
                    else
                    {
                        lblItemPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.Product.ProductPrice + cartItem.Product.AdditionalPrice);
                    }
                }
                else
                {
                    lblItemPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.UnitPrice);
                }

                TextBox tbxQuantity = (TextBox)e.Item.FindControl("tbxQuantity");
                tbxQuantity.Text = cartItem.Quantity.ToString();
                tbxQuantity.MaxLength = SiteUtility.MaximumQuantityLength;

                Label lblItemTotal = (Label)e.Item.FindControl("lblItemTotal");
                lblItemTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.ItemTotal);

                Button imbItemUpdate = (Button)e.Item.FindControl("imbItemUpdate");
                imbItemUpdate.CommandArgument = e.Item.ItemIndex.ToString();
            }
           
        }
        else if (e.Item.ItemType == ListItemType.Footer)
        {
            Label lblSubTotal = (Label)e.Item.FindControl("lblSubTotal");
            lblSubTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(_shoppingCart.SubTotal);
        }
    }

    protected void rptShoppingCart_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "UpdateCart")
            {
                int rowIndex;
                if (int.TryParse(e.CommandArgument.ToString(), out rowIndex))
                {
                    RepeaterItem rptRow = rptShoppingCart.Items[rowIndex];
                    if (rptRow != null)
                    {
                        int qty, productId;
                        TextBox tbxQuantity = (TextBox)rptRow.FindControl("tbxQuantity");
                        HiddenField hdfProductId = (HiddenField)rptRow.FindControl("hdfProductId");

                        if (tbxQuantity != null && hdfProductId != null)
                        {
                            int.TryParse(tbxQuantity.Text.ToString().Trim(), out qty);
                            int.TryParse(hdfProductId.Value.ToString(), out productId);

                            Product product = Product.Load(productId);

                            if (qty > 0)
                            {
                                CartItem cartItem = this.UpdateCartItemToShoppingCart(qty, product, "", "");
                                Label lblItemTotal = (Label)rptRow.FindControl("lblItemTotal");
                                lblItemTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.ItemTotal);
                                LoadSession();
                                Label lblSubTotal = (Label)rptShoppingCart.Controls[rptShoppingCart.Controls.Count - 1].FindControl("lblSubTotal");
                                lblSubTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(_shoppingCart.SubTotal);

                            }
                            else
                            {
                               
                                uccResponseMessage.SetFailMessage(AutoGearCommonMessage.ShoppingCartInvalidQuantity);
                                uccResponseMessage.Visible = true;
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            uccResponseMessage.SetFailMessage(AutoGearCommonMessage.CommonFailure);
            uccResponseMessage.Visible = true;
        }
    }

    protected void rptShoppingCartForGift_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
            CheckBox cbxSelectAll = (CheckBox)e.Item.FindControl("cbxSelectAll");
            cbxSelectAll.Attributes.Add("onclick", "javascript:SelectAll('" + rptShoppingCartForGift.ClientID + "','" + cbxSelectAll.ClientID + "','cbxSelect')");
        }
        else if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            GiftItem giftItem = (GiftItem)e.Item.DataItem;

            HiddenField hdnGiftId = (HiddenField)e.Item.FindControl("hdnGiftId");
            hdnGiftId.Value = giftItem.GiftID;

            Label lblToName = (Label)e.Item.FindControl("lblToName");
            lblToName.Text = giftItem.ToName;

            Label lblToEmail = (Label)e.Item.FindControl("lblToEmail");
            lblToEmail.Text = giftItem.ToEmailAddress;

            Label lblItemPrice = (Label)e.Item.FindControl("lblItemPrice");
            lblItemPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(giftItem.UnitPrice);

            TextBox tbxQuantity = (TextBox)e.Item.FindControl("tbxQuantity");
            tbxQuantity.Text = giftItem.Quantity.ToString();
            tbxQuantity.MaxLength = SiteUtility.MaximumQuantityLength;

            Label lblItemTotal = (Label)e.Item.FindControl("lblItemTotal");
            lblItemTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(giftItem.ItemTotal);

            Button imbItemUpdate = (Button)e.Item.FindControl("imbItemUpdate");
            imbItemUpdate.CommandArgument = e.Item.ItemIndex.ToString();
        }
        else if (e.Item.ItemType == ListItemType.Footer)
        {
            Label lblSubTotal = (Label)e.Item.FindControl("lblSubTotal");
            lblSubTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(_shoppingCart.GiftSubTotal);
        }
    }

    protected void rptShoppingCartForGift_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "UpdateCart")
            {
                int rowIndex;
                if (int.TryParse(e.CommandArgument.ToString(), out rowIndex))
                {
                    RepeaterItem rptRow = rptShoppingCartForGift.Items[rowIndex];
                    if (rptRow != null)
                    {
                        int qty;
                        string giftId;

                        TextBox tbxQuantity = (TextBox)rptRow.FindControl("tbxQuantity");
                        HiddenField hdnGiftId = (HiddenField)rptRow.FindControl("hdnGiftId");
                        if (tbxQuantity != null && hdnGiftId != null)
                        {
                            int.TryParse(tbxQuantity.Text.ToString().Trim(), out qty);
                            giftId = hdnGiftId.Value;
                            if (qty > 0)
                            {
                                this.UpdateGiftItemToShoppingCart(giftId, qty);

                                Response.Redirect("shopping-cart.aspx");
                            }
                            else 
                            {
                                uccResponseMessage.SetFailMessage("Gift Certificate Invalid Quantity");
                                uccResponseMessage.Visible = true;
                            }
                        }
                    }
                }
            }
        }
        catch { }
    }

    protected void imbItemRemove_Click(object sender, EventArgs e)
    {
        try
        {
            LoadSession();
            ReadWriteCustomCollection<CartItem> removeCartItems = new ReadWriteCustomCollection<CartItem>();
            foreach (RepeaterItem row in rptShoppingCart.Items)
            {
                if (row.ItemType == ListItemType.Item || row.ItemType == ListItemType.AlternatingItem)
                {
                    CheckBox cbxSelect = (CheckBox)row.FindControl("cbxSelect");
                    if (cbxSelect != null && cbxSelect.Checked)
                    {
                        HiddenField hdfProductId = (HiddenField)row.FindControl("hdfProductId");
                        int productId;
                        if (int.TryParse(hdfProductId.Value, out productId))
                        {
                            if (_shoppingCart.CartItems[row.ItemIndex].Product.ProductId == productId)
                            {
                                removeCartItems.Add(_shoppingCart.CartItems[row.ItemIndex]);
                            }
                        }
                    }
                }
            }

            ReadWriteCustomCollection<GiftItem> removeGiftItems = new ReadWriteCustomCollection<GiftItem>();
            foreach (RepeaterItem row in rptShoppingCartForGift.Items)
            {
                if (row.ItemType == ListItemType.Item || row.ItemType == ListItemType.AlternatingItem)
                {
                    CheckBox cbxSelect = (CheckBox)row.FindControl("cbxSelect");
                    if (cbxSelect != null && cbxSelect.Checked)
                    {
                        HiddenField hdnGiftId = (HiddenField)row.FindControl("hdnGiftId");

                        if (_shoppingCart.GiftItems[row.ItemIndex].GiftID.Equals(hdnGiftId.Value))
                        {
                            removeGiftItems.Add(_shoppingCart.GiftItems[row.ItemIndex]);
                        }
                    }
                }
            }

            if (removeCartItems.Count > 0 || removeGiftItems.Count > 0)
            //if (removeCartItems.Count > 0 )
            {
                for (int i = 0; i < removeCartItems.Count; i++)
                {
                    _shoppingCart.CartItems.Remove(removeCartItems[i]);
                }

                for (int i = 0; i < removeGiftItems.Count; i++)
                {
                    _shoppingCart.GiftItems.Remove(removeGiftItems[i]);
                }

                BindData();
            }

        }
        catch (Exception ex)
        {
            uccResponseMessage.SetFailMessage(AutoGearCommonMessage.CommonFailure);
            uccResponseMessage.Visible = true;
        }
    }

    protected CartItem UpdateCartItemToShoppingCart(int qty, Product product, string MetalType, string GiftWrapper)
    {
        ShoppingCart shoppingcart = AutoGearSessionManager.ShoppingCart;
        CartItem cartItem = new CartItem(product, qty, MetalType, GiftWrapper);
        shoppingcart.UpdateCartItem(cartItem);
        AutoGearSessionManager.ShoppingCart = shoppingcart;        
        return cartItem;
    }

    protected void UpdateGiftItemToShoppingCart(string giftId, int qty)
    {
        ShoppingCart shoppingcart = AutoGearSessionManager.ShoppingCart;        

        GiftItem giftItem = shoppingcart.FindGiftItemByGiftId(giftId);
        giftItem.Quantity = qty;

        shoppingcart.UpdateGiftItem(giftItem);
        AutoGearSessionManager.ShoppingCart = shoppingcart;
    }
    protected void imbContinueShopping_Click1(object sender, EventArgs e)
    {
        if(string.IsNullOrEmpty(SupplierId))
        {
            Response.Redirect(CustomSiteMap.Home);
        }
        else
        {
            Response.Redirect("~/partner/" + SupplierId);
        }
    }

    protected void imbCheckout_Click(object sender, EventArgs e)
    {
        if (cbxAccept.Checked)
        {
            if (AutoGearSessionManager.ShoppingCart.SubTotal >= SiteSettings.MinimumOrderAmount || AutoGearSessionManager.ShoppingCart.GiftSubTotal >= SiteSettings.MinimumOrderAmount)
            {
                Session["check"] = null;
                Session["minAmount"] = null;
                Session["check"] = string.Empty;

                string imageUrl = string.Empty;
                if (SessionManager.IsUserLoggedIn)
                {
                    AutoGearSessionManager.CheckoutSteps = CheckoutSteps.PreCheckout;
                   
                    AutoGearSessionManager.ShoppingCart.MultipleShipAdd = null;
                    String redirectUrl = string.IsNullOrEmpty(SupplierId) ? CustomSiteMap.OrderSummary : "~/partner/" + SupplierId + "/order-summary.aspx";
                    Response.Redirect(redirectUrl);

                }
                else
                {
                    AutoGearSessionManager.CheckoutSteps = CheckoutSteps.ShoppingCart;
                    
                    AutoGearSessionManager.ShoppingCart.MultipleShipAdd = null;
                    String redirectUrl = string.IsNullOrEmpty(SupplierId) ? CustomSiteMap.PreCheckout : "~/partner/" + SupplierId + "/pre-checkout.aspx";                    
                    Response.Redirect(redirectUrl);
                }
            }
            else 
            {
                uccResponseMessage.SetFailMessage("You have not met the minimum order requirement of $" + SiteSettings.MinimumOrderAmount.ToString() + "");
                uccResponseMessage.Visible = true;
            }
        }
        else
        {
            uccResponseMessage.SetFailMessage(AutoGearCommonMessage.ShoppingCartAcceptTermsCondition);
            uccResponseMessage.Visible = true;
        }
    }

    private void CheckoutStepsValidate()
    {
        ContentPlaceHolder ph = (ContentPlaceHolder)this.Master.Master.FindControl("cphMiddleContent");

        Literal litPageTitle = (Literal)ph.FindControl("litPageTitle");
        Literal litCurrentPage = (Literal)ph.FindControl("litCurrentPage");

        if (litPageTitle != null)
        {
            litCurrentPage.Text = litPageTitle.Text = "Shopping Cart";

        }
    }
}
